package com.synjones.handsetS8;

import android.content.Context;
import android.os.AsyncTask;

/**
 * Created by zhaodianbo on 2018-6-25.
 */
public class BarReaderModule {

    private static BarReaderModule barReaderModule;
    private Context context;
    private BarReader barReader;
    final byte SCAN_CMD[] = util_debug.hexString2bytes("1b31");

    private BarReaderModule(Context context) {
        this.context=context;
        barReader=new BarReader(context);
    }

    public static BarReaderModule getInstance(Context context){
        if(barReaderModule==null){
            barReaderModule=new BarReaderModule(context);
        }
        return barReaderModule;
    }

    public int open(){
        if(barReader==null) return -10;
        return barReader.open();
    }

    public int close(){
        if(barReader==null) return -10;
        return barReader.close();
    }

    public void scan(OnScanResult onScanResult){

        if(barReader==null){
            if(onScanResult!=null)
                onScanResult.onScanResult(new BarScanResult(BarScanResult.ERR_INSTANCE));
            return;
        }

        if(!barReader.isOpen()){
            if(onScanResult!=null)
                onScanResult.onScanResult(new BarScanResult(BarScanResult.ERR_NOT_OPEN));
            return;
        }

        if(barReader.isScanning()){
            barReader.sendCmd(SCAN_CMD);
            if(onScanResult!=null)
                onScanResult.onScanResult(new BarScanResult(BarScanResult.ERR_BUSY));
            return;
        }

        new RecvMsgAsyncTask(onScanResult).execute();

        barReader.sendCmd(SCAN_CMD);
    }

    public BarReader getBarReader() {
        return barReader;
    }

    public boolean isScanning() {
        if(barReader==null) return false;
        return barReader.isScanning();
    }

    public void cancel(){
        if(barReader!=null)
            barReader.stopScan();
    }

    class RecvMsgAsyncTask extends AsyncTask<Void, Void, BarScanResult> {
        BarScanResult barScanResult;
        OnScanResult onScanResult;
        public RecvMsgAsyncTask(OnScanResult onScanResult) {
            this.onScanResult=onScanResult;
        }

        @Override
        protected BarScanResult doInBackground(Void... params) {
            long t = System.currentTimeMillis();
            barScanResult = barReader.getScanResult();
            return barScanResult;
        }

        @Override
        protected void onPostExecute(BarScanResult barScanResult) {
            super.onPostExecute(barScanResult);
            if(onScanResult!=null)
                onScanResult.onScanResult(barScanResult);
        }
    }

    public interface OnScanResult{
        void onScanResult(BarScanResult barScanResult);
    }
}
